/*
 * Copyright Owen Watson 2009
 * 
 * This file is part of ArtNotes.
 *
 * ArtNotes is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * ArtNotes is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with ArtNotes.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.CoreGraphics;
using System.IO;
using MonoTouch.CoreLocation;

namespace ArtNotes
{
	/// <summary>
	/// In a similar manner the Notebooks Tab Controller
	/// this provides a tabular view of the images present
	/// within a notebook, giving a thumbnail and the
	/// title / description of an item.
	/// Selecting a row in the table will change the view
	/// to show more detailed information about an
	/// image.
	/// </summary>
	[MonoTouch.Foundation.Register("ANNotebook")]
	public class ANNotebookController : UITableViewController
	{
		public ANNotebookController (IntPtr p) : base(p)
		{
		}
		
		public ANNotebookController ()
		{
		}
		
		private UIAlertView resetConfirm;		
		
		private CLLocationManager locationManager;
		
		private string TagName = "Not Set!";
		
		private ANDatabase anDB;
		
		public ANNotebookController (string tagName)
		{
			this.TagName = tagName;
		}

		class DataSource : UITableViewDataSource {
			
			ANNotebookController nvc;
			const int kViewTag = 1;
			
			private Dictionary<int, anTableViewCell> controllers = null;
				
			public DataSource (ANNotebookController  nvc)
			{
				this.nvc = nvc;
				controllers = new Dictionary<int, anTableViewCell>();
			}

			public override int RowsInSection (UITableView tableView, int section)
			{
				if(nvc.isEmpty)
					return 1;
				else
					return nvc.notebookItems.Length;
			}
			
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				if(nvc.isEmpty)
				{
					UITableViewCell cell;
					cell = tableView.DequeueReusableCell ("emptyCell");
					if (cell == null) {
						cell = new UITableViewCell (UITableViewCellStyle.Default, "emptyCell");
						cell.SelectionStyle = UITableViewCellSelectionStyle.None;
					} else {
						// The cell is being recycled, remove the old content

						UIView viewToRemove = cell.ContentView.ViewWithTag (1);
						if (viewToRemove != null)
							viewToRemove.RemoveFromSuperview ();
					}
					cell.TextLabel.Text = "Your Notebook. It is Empty.";
					return cell;
				}
				else
				{
					anTableViewCell cellController = null;
					
					UITableViewCell cell = tableView.DequeueReusableCell ("anCell");
					
					if (cell == null)
	          		{
						cellController = new anTableViewCell ();
	
						NSBundle.MainBundle.LoadNib ("anTableViewCell", cellController, null);
						cell = cellController.Cell;
						
						cell.Tag = Environment.TickCount;
						controllers.Add (cell.Tag, cellController);
					}
					else
					{
						cellController = controllers[cell.Tag];
					}
					
	
					cellController.anCustomImageView.AutosizesSubviews = true;
					
					Random random = new Random ();
					float rotation = (float)(Math.PI * random.Next (-5, 5) / 180.0) ;
					
					// -----
					// HACK: needs fixing
					ANImageUtils imageUtils = new ANImageUtils();
					UIImage frame = UIImage.FromFile("Images/polaroid.png");
					UIImage tmp = imageUtils.overlayImageWithPolaroid(
						nvc.notebookItems[indexPath.Row].Image,
						frame,
						new RectangleF (0, 0, 75, 75),
						new RectangleF (0, 0, 75, 75),
						new SizeF (75, 75)
						);
					// -----
					
					cellController.anCustomImageView.Image = tmp;
					cellController.anCustomImageView.Transform = CGAffineTransform.MakeRotation (rotation);
					
					cellController.anCustomTitle = nvc.notebookItems[indexPath.Row].Title;
					cellController.anCustomDescription = nvc.notebookItems[indexPath.Row].Description;
					
					return cell;
				}
			}
		}
	
		class TableDelegate : UITableViewDelegate {
			
			ANNotebookController nvc;
		
			public TableDelegate (ANNotebookController  nvc)
			{
				this.nvc = nvc;
			}
			
			public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
			{
				return 95f;
			}
		
			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				Console.WriteLine ("Row selected {0}", indexPath.Row);
		
				if(!nvc.isEmpty)
				{
					// constructor should take image id from value of row
					ANImageInfoController imageInfoController = new ANImageInfoController (nvc.notebookItems[indexPath.Row].ImageID);
					Console.WriteLine("ImageID : " + nvc.notebookItems[indexPath.Row].ImageID.ToString());
					tableView.DeselectRow(indexPath, true);
					nvc.NavigationController.PushViewController (imageInfoController, true);
				}
			}
		}
		
		struct NotebookItem
		{
			public string Title, Description;
			public UIImage Image;
			public int ImageID;

			public NotebookItem (string title, string description, UIImage image, int imageId)
			{
				Title = title; 
				Description = description;
				Image = image;
				ImageID = imageId;
			}
		}

		private NotebookItem[] notebookItems;
		
		private UIImage LoadImage (string filename)
		{
			UIImage img = UIImage.FromFileUncached(AN_APP_OPTIONS.THUMB_DIR + filename);
			return img;
		}
		
		public override void ViewDidLoad ()
		{
			Console.WriteLine ("ANNotebookController: ViewDidLoad()");
			base.ViewDidLoad ();

			locationManager = AN_APP_OPTIONS.AN_LOCATION;
			
			anDB = AN_APP_OPTIONS.AN_DATABASE;
			this.TableView.BackgroundColor = UIColor.Clear;
			this.TableView.SeparatorColor = UIColor.Clear;
			this.ParentViewController.View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("Images/notepaper.png"));
			
			NavigationItem.BackBarButtonItem = new UIBarButtonItem () { Title = "Back" };
			
			this.TableView.DataSource = new DataSource (this);
			this.TableView.Delegate = new TableDelegate (this);
			
			UIBarButtonItem btnImport = new UIBarButtonItem();
			btnImport.Title = "Import";
			btnImport.Clicked += delegate {
				Console.WriteLine("ImportButtonPressed");
				
				UIActionSheet importOption = new UIActionSheet();
				importOption.AddButton("Camera");
				importOption.AddButton("Photo Library");
				importOption.AddButton("Cancel");
				
				importOption.Clicked += importOptionSelector;
				
				importOption.Title = "Choose Source";
				importOption.ShowInView(this.View);
			};
			
			this.NavigationItem.SetRightBarButtonItem(btnImport,false);
			isEmpty = false;
			
			/*var f = new RectangleF (0f, 0f, View.Bounds.Width, 44f);
			bar = new UISearchBar (f){
				Delegate = new SearchDelegate (),
				ShowsCancelButton = true,
			};
			View.AddSubview (bar);*/
		}
		
		/*private UISearchBar bar;
	
		class SearchDelegate : UISearchBarDelegate {
			public override void SearchButtonClicked (UISearchBar bar)
			{
				bar.ResignFirstResponder ();
			}
	
			public override void CancelButtonClicked (UISearchBar bar)
			{
				bar.ResignFirstResponder ();
			}
		}*/
		
		private ANImportImageFromDevice anImportImage;
		
		void importOptionSelector(object sender, UIButtonEventArgs e)
		{
			//Tag t = new Tag();
			//t.TagName = this.Title;
			
			if(e.ButtonIndex.Equals(0))
			{
				Console.WriteLine("camera");
				anImportImage = new ANImportImageFromDevice(true);//,t);
				this.NavigationController.PresentModalViewController(anImportImage,true);
			}
			else if(e.ButtonIndex.Equals(1))
			{
				Console.WriteLine("photolibrary");
				anImportImage = new ANImportImageFromDevice(false);//,t);
				this.NavigationController.PresentModalViewController(anImportImage,true);
				
				//if(anImportImage.ImportedImage != null)
				//{
				//	Tag[] tags = new Tag[1];
				//	tags[1] = new Tag() {TagName = this.Title};
				//	Console.WriteLine("\n\n\n\nSaving Image\n\n\n\n\n");
				//	this.saveImage(anImportImage.ImportedImage,tags);
				//	Console.WriteLine("\n\n\n\n\nSaved Image\n\n\n\n\n\n");
				//}
				//else
				//	Console.WriteLine("\n\n\n\n\nImage is null!\n\n\n\n\n");
			}
		}
		
		private bool isEmpty;
		public override void ViewWillAppear (bool animated)
		{	
			base.ViewWillAppear(animated);
			try
			{	
				
				if(anImportImage != null)
				{
					if(anImportImage.ImportedImage != null)
					{					
						Tag[] tags = new Tag[1];
						tags[0] = new Tag() {TagName = this.Title};
						this.saveImage(anImportImage.ImportedImage,tags);
						this.anImportImage = null;
					}
				}
				
				this.Title = this.TagName;
				Tag tag = anDB.GetTagByName(this.TagName);
				
				Image[] notebookImages = anDB.ListImagesForTag(tag).ToArray();
				
				//Console.WriteLine("notebook images length : " + notebookImages.Length.ToString());
				
				notebookItems = new NotebookItem[notebookImages.Length];
				
				for(int i =0; i < notebookImages.Length;i++)
				{
					Console.WriteLine("imagefilename : " + notebookImages[i].ThumbFileName);
					
					notebookItems[i] = new NotebookItem(
	                    notebookImages[i].Title,
	                    notebookImages[i].Description,
	                    LoadImage(notebookImages[i].ThumbFileName),
	                    notebookImages[i].Id
					);
					//Console.WriteLine("imageid : " + notebookImages[i].Id.ToString());

				}
				
				this.TableView.ReloadData();
			}
			catch(Exception e)
			{
				//Console.WriteLine("\n\n\n\nException\n\n\n\n");
				isEmpty = true;
				this.TableView.ReloadData();
				//this.NavigationController.PopViewControllerAnimated(true);
				//this.NavigationController.NavigationBar.PopNavigationItemAnimated(true);
			}

			Console.WriteLine("\nAppeared\n");
		}
		
		private bool saveImage(UIImage image, Tag[] tags)
		{
			try {
				ANImageUtils anImageUtils = new ANImageUtils();
				string randomName = Path.ChangeExtension(Path.GetRandomFileName(), ".jpg");
				Image img = new Image();
				
				UIImage imgThumb = anImageUtils.resizeImage(image, new SizeF(75,75));
				
				NSError err= null;
				NSData imgData = image.AsJPEG();
				imgData.Save(AN_APP_OPTIONS.DOC_DIR + randomName, false, out err);
				
				imgData = imgThumb.AsJPEG();
				imgData.Save(AN_APP_OPTIONS.THUMB_DIR + AN_APP_OPTIONS.THUMB_PREFIX + randomName, false, out err);
				
				img.FileName = randomName;
				img.ThumbFileName = AN_APP_OPTIONS.THUMB_PREFIX + randomName;
				img.Title = "Imported Image";
				img.Description = DateTime.Now.ToString();
				if(this.locationManager != null)
				{
					img.Lattitude = this.locationManager.Location.Coordinate.Latitude;
					img.Longitude = this.locationManager.Location.Coordinate.Longitude;
				}
				
				this.anDB.CreateImage(img,tags);
				
				return true;
			}
			catch(Exception e)
			{
				return false;
			}
		}

	}
}
